#include "cboard.h"
#include "cplayer.h"
#include "csocket.h"
#include <string>
#include <iostream>
#include <fstream>
#include <cstdio>
#include <vector>

using namespace std;
using namespace sokoban;

int main(int pArgC, char* pArgs[])
{
  // Respect the functionality without parameters for testing
  if ( pArgC==1 )
  {
    string str, stringBoard;
    ifstream fin ("board.in", ifstream::in);

    if ( fin.good() )
    {
      while ( getline(fin, str) )
      {
        stringBoard += str;
        stringBoard += '\n';
        str.clear();
      }
    }
    else
    {
      printf("Error reading from board.in!\n"); 
      return -1;
    } 

    CBoard testBoard ( stringBoard );
    testBoard.Print();

    CPlayer player;
    cout << "entering placeBoxes" << endl;
    string solution = player.PlaceBoxes( testBoard );
    cout << "place boxes done" << endl;
    printf("%s\n", solution.c_str());
    return 0;
  }
  else if ( pArgC!=4 )
  {
    cerr << "usage: " << pArgs[0] << " host port boardnum" << endl;
    return -1;
  }
  
  soko::CSocket lSocket(pArgs[1],pArgs[2]);

  lSocket.WriteLine(pArgs[3]);
    
  std::string lLine, strBoard;

  //read number of rows
  lSocket.ReadLine(lLine);
  int lNumRows=atoi(lLine.c_str());
    
  //read each row
  strBoard = "";
  for(int i=0;i<lNumRows;i++)
  {
    lSocket.ReadLine(lLine);
    //here, we would store the row somewhere, to build our board
    //in this demo, we just print it
    //std::cout << lLine << "\n";
    strBoard += lLine;
    strBoard += "\n";
  }
  
  printf("%s", strBoard.c_str());
  CBoard board( strBoard );

  //now, we should find a solution to the sokoban
  CPlayer player;
  string lMySol = player.PlaceBoxes( board );
  printf("%s\n", lMySol.c_str());

  //we've found our solution (this is actually the solution to board 1)    
  //std::string lMySol("U R R U U L D L L U L L D R R R R L D D R U R U D L L U R");
  //these formats are also valid:
  //std::string lMySol("URRUULDLLULLDRRRRLDDRURUDLLUR");
  //std::string lMySol("0 3 3 0 0 2 1 2 2 0 2 2 1 3 3 3 3 2 1 1 3 0 3 0 1 2 2 0 3");

  //send the solution to the server
  lSocket.WriteLine(lMySol);
    
  //read answer from the server
  lSocket.ReadLine(lLine);
    
  std::cout << lLine << std::endl;

  return lLine.compare("CORRECT SOLUTION");
}
